<!--  -->
<template>
  <div class="main">
    <h2>机构分类管理</h2>
    <el-button type="primary" style="margin:20px" @click="()=>{editType=1;editVisible=true;title='添加状态';orgType.id='无需填写'}">添加分类</el-button>

    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <!-- <el-table-column
          align="center"
          prop="id"
          label="编号"
          min-width="15%"
        /> -->

        <el-table-column
          label="序号"
          type="index"
          min-width="15%"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="typeName"
          label="名称"
          min-width="35%"
        />

        <el-table-column
          align="center"
          prop="state"
          label="状态"
          min-width="20%"
        >
          <template slot-scope="Scope">
            <span v-if="Scope.row.state==0" style="color:red">关闭</span>
            <span v-if="Scope.row.state==1" style="color:green">开启</span>

          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" min-width="30%">
          <template slot-scope="Scope">
            <el-button type="primary" icon="el-icon-edit" @click="editVisible=true; orgType={};editType=2;title='修改分类';orgType=Scope.row;orgType.state=String(orgType.state)">修改</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.id,Scope.row.typeName)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5,10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

    </div>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="editVisible" @close="handleClose">
      <el-form ref="orgType" :model="orgType" label-position="top" :rules="rules">

        <!-- <el-form-item label="机构分类编号：" :label-width="formLabelWidth">
          <el-input v-model="orgType.id" autocomplete="off" readonly="" />
        </el-form-item> -->

        <el-form-item prop="typeName" label="分类名称：" :label-width="formLabelWidth">
          <el-input v-model="orgType.typeName" autocomplete="off" maxlength="20" show-word-limit />
        </el-form-item>

        <el-form-item prop="state" label="状态：" :label-width="formLabelWidth">
          <el-select v-model="orgType.state" placeholder="请选择">
            <el-option key="0" label="关闭" value="0" />
            <el-option key="1" label="开启" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button v-if="editType==2" type="primary" @click="handleUpdate('orgType')">修 改</el-button>
        <el-button v-if="editType==1" type="primary" @click="handleAdd('orgType')">添 加</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getAllOrgType, addOrgType, deleteOrgType, updateOrgType } from '@/api/orgType'
export default {
  name: 'OrgType',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    // 这里存放数据
    return {
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      list: [],
      listLoading: true,
      editVisible: false,
      orgType: {
        typeName: '',
        state: ''
      },
      editType: 0, // 添加 1  修改 2,
      title: '',
      rules: {
        typeName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }, { validator: this.validateCharacter, trigger: ['blur', 'change'] }],
        state: [{ required: true, message: '分类状态不能为空', trigger: 'blur' }]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.fetchData()
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    fetchData() {
      this.listLoading = true
      getAllOrgType().then((data) => {
        this.list = data.obj
        this.listLoading = false
      })
    },
    handleClose() {
      this.orgType = {}
      this.editVisible = false
    },
    handleDelete(id, name) {
      this.$confirm('确认删除该分类？分类名称为:' + name).then(() => deleteOrgType(id).then((data) => {
        this.$notify({
          title: '操作成功',
          type: 'success'
        })
        const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
        const page = this.currentPage > totalPage ? totalPage : this.currentPage
        this.currentPage = this.currentPage < 1 ? 1 : page
        this.fetchData()
      }))
    },
    handleAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addOrgType(this.orgType.typeName, this.orgType.state).then((resp) => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
            this.consoleUser = {}
            this.editVisible = false
          })
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateOrgType(this.orgType.id, this.orgType.typeName, this.orgType.state).then((resp) => {
            this.$notify({
              title: '操作成功',
              message: '分类信息已更新',
              type: 'success'
            })
            this.orgType = {}
            this.editVisible = false
          })
          this.editVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    checkSpecificKey(str) {
      var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'"
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
          return false
        }
      }
      return true
    },
    // 验证字符串
    validateCharacter(rule, value, callback) {
      if (this.checkSpecificKey(value)) {
        callback()
      } else {
        callback(new Error('请不要输入特殊字符'))
      }
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style  scoped>

</style>
